import React, {Component} from 'react';
import DynamicTabNavigator from "../navigator/DynamicTabNavigator";
import NavigationUtil from "../navigator/NavigationUtil";
import {BackHandler} from 'react-native';
import {NavigationActions} from 'react-navigation';
import {connect} from "react-redux";

type Props = {};
class HomePage extends Component<Props> {

  // 组件挂载时，监听物理返回事件
  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
  }
  // 组件卸载时，移除事件监听
  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
  }

  // 处理Android下的物理返回键
  onBackButtonPressAndroid = () => {
    const {dispatch, nav} = this.props;
    if (nav.routes[1].index === 0) { // nav.routes[1]为RootNavigator中的MainNavigator，MainNavigator的index为0时表示无可返回的页面
      return false;
    } else {
      dispatch(NavigationActions.back());
      return true;
    }
  };

  render() {
    // 保存当前状态的navigation
    NavigationUtil.navigation = this.props.navigation;
    // 返回一个动态底部导航器
    return <DynamicTabNavigator/>;
  }
}

/**
 * 订阅nav，将state中的nav映射到组件props中的nav属性
 * @param state
 * @returns {{nav: *}}
 */
const mapStateToProps = state => ({
  nav: state.nav
});

/**
 * 连接 React组件 与 Redux Store
 */
export default connect(mapStateToProps)(HomePage);
